<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\controller\admin;

use app\book\base\BookAdminBase;

use app\book\model\Book;
use app\book\model\BookData;
use app\book\model\BookCategory;
use app\book\model\Chapter;

class Index extends BookAdminBase{
    //当前控制器菜单
    public $submenu = [];

    /**
     * TP初始化方法
     */
    public function _initialize() {
        parent::_initialize();
        $this->submenu[] = ['title' => '图书列表', 'url' => url('book/admin.index/index'), 'icon' => '&#xe60a;'];
        $this->submenu[] = ['title' => '添加图书', 'url' => url('book/admin.index/add'), 'icon' => '&#xe608;'];
    }

    /**
     * 后台图书列表
     * @access public
     * @return \think\Response
     */
    public function index(BookCategory $book_category){
        $list = Book::order('update_time desc,id desc')->paginate(config('mn_admin.admin_pagesize'));
        $this->assign([
            'submenu' => $this->submenu,
            'list' => $list,
            'categorys' => $book_category->getTreeOption()
        ]);
    	return $this->fetch();
    }

    /**
     * 后台图书增加
     * @access public
     * @return \think\Response
     */
    public function add(Book $book, BookCategory $book_category){
        // POST提交数据
        if($this->request->isPost()){
            //获取提交的数据
            $post_data = $this->buildParam();
            $post_data['volumes'] = $book->checkVolume($post_data['volumes']);
            if(false === $post_data['volumes']){
                $this->error($book->getError());
            }
            // 验证主表字段
            $validate_result = $this->validate($post_data,'Book');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'BookData');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 启用事务
            $book->startTrans();
            try{
                if($book->allowField(true)->save($post_data)){
                    $book_data = new BookData;
                    $book->bookData()->save($book_data);
                }
                $book->commit();
            } catch (\Exception $e) {
                // 回滚事务
                $book->rollback();
                $this->error($e->getFile().':'.$e->getLine().':'.$e->getMessage(),null,'',10);
            }
            $this->success('操作成功','index');
        }
        $this->assign([
            'submenu' => $this->submenu,
            'categorys' => $book_category->getTreeOption()
        ]);
        return $this->fetch();
    }

    /**
     * 后台图书修改
     * @access public
     * @return \think\Response
     */
    public function edit($id = 0, BookCategory $book_category){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少参数id','index');
        }
        // 查询图书信息
        $book = Book::get($id);
        if(!$book){
            $this->error('图书不存在','index');
        }
        // POST提交数据
        if($this->request->isPost()){
            //获取提交的数据
            $post_data = $this->buildParam();
            $post_data['volumes'] = $book->checkVolume($post_data['volumes']);
            if(false === $post_data['volumes']){
                $this->error($book->getError());
            }
            // 验证主表字段
            $validate_result = $this->validate($post_data,'Book');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'BookData');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 启用事务
            $book->startTrans();
            try{
                if(false !== $book->allowField(true)->save($post_data,['id'=>$book->id])){
                    //$book->book_data->save();
                }
                $book->commit();
            } catch (\Exception $e) {
                // 回滚事务
                $book->rollback();
                $this->error($e->getFile().':'.$e->getLine().':'.$e->getMessage(),null,'',10);
            }
            $this->success('操作成功','index');
        }
        $this->assign([
            'submenu'   => $this->submenu,
            'data'      => $book->getData(),
            'categorys' => $book_category->getTreeOption((int)$book->getData('catid'))
        ]);
        return $this->fetch();
    }

    /**
     * 后台图书删除
     * @access public
     * @return void
     */
    public function del($id = 0){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少图书参数id');
        }
        $book = Book::get($id);
        if(!$book){
            $this->error('图书不存在');
        }
        // 删除封面
        if(!empty($book->cover)){
            $cover_path = '.'.str_replace('\\', '/', $book->cover);
            if(is_file($cover_path)){
                if(!unlink($cover_path)){
                    $this->error('图书封面删除失败，请检查权限！', 'index');
                }
            }
        }
        /*
        // 删除章节
        $chapters = Chapter::all(['book_id'=>$book->id]);
        foreach ($chapters as $key => $chapter) {
            $chapter->together('chapter_data')->delete();
        }
        */
        // 删除图书
        //$book->delete();
        //$book->book_data->delete();
        $book->together('book_data')->delete();
        $this->success('图书删除成功', 'index');
    }
}